﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wedo.Recognition.Domain.Models;
using Wedo.Recognition.Domain;
using Wedo.Service.Common;
using Wedo.Utility.Log;
using Wedo.Recognition.Domain;
using Wedo.Recognition.Repository;


namespace Wedo.Recognition.Service
{
    /// <summary>
    /// 出口凭证
    /// </summary>
    public  class TransferVoucherService: BaseService<TransferVoucher> 
    {
        private BankDataService BankService;

        public TransferVoucherService(IUnitWork dbContext)
            : base(dbContext, dbContext.Set<TransferVoucher>())
        {
            BankService = new BankDataService(dbContext);
        } 

        private List<BankData> BankDataUpdateWithTV = new List<BankData>();
        private List<TransferVoucher> TransferVoucherAddWithTV = new List<TransferVoucher>();

        /// <summary>
        /// 生成转账单
        /// </summary>
        /// <returns></returns>
        public bool CreateTransferVoucher()
        {
            var bankData = this.GetBankDataNeedToTV();
            DateTime now = DateTime.Now;
            foreach (var _bankData in bankData)
            {
                var paymentApply = _bankData.PaymentApply
                    .OrderBy(m => m.Created).FirstOrDefault();
 
                if (paymentApply != null && paymentApply.CustomerCode != _bankData.CustomerCode)
                {
                    //生成转账凭证
                    //账单编号，银行名称，付款人，实收金额,DocumentNo,原客户编号，新客户编号
                    TransferVoucherAddWithTV.Add(new TransferVoucher
                    {
                        Id = Guid.NewGuid(),
                        Created=now,
                        Assiginment = _bankData.Assiginment,
                        BankCode = _bankData.BankCode,
                        Payer = _bankData.Payer,
                        BankPaidIn = _bankData.BankPaidIn,
                        DocumentNo = _bankData.DocumentNo,
                        OriginalCustomerCode = _bankData.CustomerCode,
                        NewCustomerCode = paymentApply.CustomerCode,
                        SONO=_bankData.SONO(),
                        NewDocumentNo=""
                    });
                    BankDataUpdateWithTV.Add(_bankData);
                }
                else
                {
                    //不生成转账凭证
                    Logger.LogInfo("TransferVoucherService", "CreateRecieveVoucher", 0, string.Format("BankDataID:{0} Is Not Need To Generate TransferVoucher.", _bankData.Id),null);
                }
            }
            return UpdateDBWithTV();
        }

       /// <summary>
       /// 修改数据
       /// </summary>
       /// <returns></returns>
        private bool UpdateDBWithTV()
        {
            if (BankDataUpdateWithTV.Count == 0)
            {
                //没有凭证可以生成
                Logger.LogInfo("TransferVoucherService", "CreateRecieveVoucher", 0, "Not Found Any Data Need To Generate TransferVoucher.", null);
                return false;
            }

            try
            {
                DateTime now = DateTime.Now;

                for (int i = 0; i < BankDataUpdateWithTV.Count;i++ )
                {
                    BankDataUpdateWithTV[i].GenerateTransferVoucher = true;
                    BankDataUpdateWithTV[i].GenerateTransferDate = now;
                    // BankService.Update(_bankData);
                }
                foreach (var _transferVoucher in TransferVoucherAddWithTV)
                {
                    _repository.Create(_transferVoucher);
                }
                Commit();
                return true;

            }
            catch (Exception e)
            {
                //数据库写入失败
                StringBuilder bankId = new StringBuilder();
                BankDataUpdateWithTV.ForEach(t => bankId.AppendLine(t.Assiginment));
                Logger.LogInfo("TransferVoucherService", "UpdateDBWithTV", 0, string.Format("DataBase Error. BankDataIds:{0}", bankId.ToString()), e.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取已经生成收款凭证，被导入SAP，没有生成转账凭证的银行账单
        /// </summary>
        /// <returns></returns>
        private List<BankData> GetBankDataNeedToTV()
        {

            //获取已经生成收款凭证，被导入SAP，没有生成转账凭证的银行账单
            return _dbContext.Set<BankData>().Filter(
                t => t.IsDelete == false 
                    && t.GenerateRecieveVoucher == true && t.ImportSAP == true
                    && t.GenerateTransferVoucher == false && t.Status == 1
                 ).ToList();
        }

        /// <summary>
        /// 查询第一个认款单
        /// </summary>
        /// <param name="bankData"></param>
        /// <returns></returns>
        private PaymentApply GetPaymentApplyNeedToTV(BankData bankData)
        {
            var paymentApply = _dbContext.Set<PaymentApply>()
                .Find( t => t.BankDataId == bankData.Id);
            if (paymentApply != null && paymentApply.CustomerCode != bankData.CustomerCode)
            {
                return paymentApply;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 凭证确认处理
        /// </summary>
        /// <param name="id">批量处理的ID</param>
        public void TransferVoucherConfirm(string id)
        {
            try
            {

                var guids = new List<Guid>();
                id.Split(',').ToList().ForEach(s => guids.Add(Guid.Parse(s)));
                IList<TransferVoucher> list = _repository.All().Where(s => guids.Any(m => m == s.Id)).ToList();

                for(int i=0;i<list.Count;i++ )
                {
                    list[i].HasConfirm = true;
                }
                Commit();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        
        }
    }
} 